////// window with list of servers
var modServerList = new Class({
  Extends: boxWindow,
    options: {
        BtnRefresh: false,
        BtnMin: false,
        BtnSettings: false,
        title: lang.label('server_setting'),
        name: 'modServerList',
        uniqueCss: true,
        modal: true,
        BtnClose: true,
        fixed: false,
        left: 0,
        top: 0,
        width: 790,
        isBox: false
    },
    // the server list table
    table_id: 'server_list',
    // image while loading connection status
    status_img: '<img class="status_img" src="' + homeBase + 'img/default/widgetLoading.gif" />',
    // 
    refresh_icon: homeBase + 'img/default/icon_refresh.gif',
    lost_connection: [],
    timeout_connection: [],
    adding: false,
    // indicate if the status is adding server
    firstproxyid: null,
    hasProxy: false,
    scanservercheckarray: {},
    proxylistcheckarray: null,
    serverlistcheckarray: null,
    NeedToopenOpts: false,
    objSelectedServerHash: new Hash(),

    ///// get where to display the box
    initialize: function (NeedToopenOpts) {
        // URL of connectionstatus query
        this.NeedToopenOpts = NeedToopenOpts;
        this.parent();
    },

    showMsg: function (msg, type) {
        messageMaker('messageBox', {
            msg_type: type ? type : 'error',
            closeBtn: false,
            collapsed: true,
            fadeOut: false,
            message: msg + '<a href="javascript:void(0);" onclick="return toggleMsg(this);" class="icon_show"></a>'
        });
        var el = $('messageBox').getElement('.message_content');
        var icon_link = el.getFirst('a');
        if (icon_link){
            icon_link.setStyle('display', el.offsetHeight != el.scrollHeight ? '' : 'none');
        }
        this.updateNotesLocation();
    },

    updateNotesLocation:function(){
      $('del_server_note').removeEvents('click');
      $('refresh_server_note').removeEvents('click');
        var del_server_Coordinates=$('del_server').getCoordinates($('modaloverlay'));
        $('del_server_hint').setPosition({x:del_server_Coordinates.right-4,y:del_server_Coordinates.top-1}).setStyle('display','block');
        $('del_server_note').addEvent('click', this.delServerNote.bind(this));
        var refresh_server_Coordinates=$('refresh_server').getCoordinates($('modaloverlay'));
        $('refresh_server_hint').setPosition({x:refresh_server_Coordinates.right-4,y:refresh_server_Coordinates.top-1}).setStyle('display','block');
        $('refresh_server_note').addEvent('click', this.refreshServerNote.bind(this));
    },
    /////// load the info in the box
    onFinish: function () {
        var mainobj = this;
        var divMain = null;
        var posx = (getWidth() / 2) - (this.options.width / 2);
        var posy = (getHeight() / 2) - (this.options.height / 2);
        var overLay = $('modaloverlay');
        var modCss = this.options.uniqueCss ? this.options.name : '';

        if (this.options.isBox) {
            overLay.setStyle('width', this.options.width + 'px');
            overLay.setStyle('height', this.options.height + 'px');
            overLay.setStyle('top', posy);
            //overLay.setStyle('left', posx); 
        } else {
            overLay.setStyle('width', this.options.width + 'px');
            overLay.setStyle('top', 50);
            //overLay.setStyle('left', posx); 
        }


        // filling title
        this.fillTitle(this.options.title);

        // content box
        this.contentBox.setHTML(
        // update info
        '<div id="updateText"></div>' +
        // message box
        '<div id="messageBox"></div>' +
        // add server link
        '<table id="button_table"><tr><td><input id="add_server" type="button" value="'+lang.labelText('add_server')+'"/>' +'<input id="del_server" type="button" value="'+lang.labelText('del_server')+'"/>'+'<div id="del_server_hint" style="font-size: 1px;position: absolute;width: 1px; height: 1px; overflow: visible;display:none;" ><div id="del_server_note" style="left: 0pt; top: 0pt;" class="annnotelabel">'+lang.label('questionmark')+'</div></div>'+'<input id="refresh_server" type="button" value="'+lang.labelText('refresh')+'"/>'+'<div id="refresh_server_hint" style="font-size: 1px;position: absolute;width: 1px; height: 1px; overflow: visible;display:none;" ><div id="refresh_server_note" style="left: 0pt; top: 0pt;" class="annnotelabel">'+lang.label('questionmark')+'</div></div>'+'</td></tr></table>'+
        //contents 
        '<table id="serv_list_table" cellspacing="0" cellpadding="0" width="100%">' +
        //'<tr><td class="handler server_list">'+lang.label('server_list')+'</td></tr>'+
        '<tr><td class="window_content">' +
        // server list
        '<table cellspacing="0" cellpadding="0" width="100%" class="datagrid" id="' + this.table_id + '"><tbody>' + '<tr>'+ '<th width="5%" style="text-align:center;"><input id="checkAll" type="checkbox" value="checkbox"></th>' + '<th width="50%">' + lang.label('cloud_url') + '</th>' + '<th width="40%">' + lang.label('type') + '</th>' + '<th width="5%">' + lang.label('edit') + '</th>'+ '</tr>' + '</tbody></table>' + '</td></tr>' +'</table>'+
        '<p>&nbsp</p>' +
        // proxy server
        '<table id="proxy_table" cellspacing="0" cellpadding="0" width="100%"><tr><td class="handler proxy_setting">' + lang.label('proxy_setting') + '<span id="proxy_toggle" class="btn_show"></span></td></tr>' + '<tr id="proxy_content"><td class="window_content" style="border-top:1px solid #999999">' + '<table cellspacing="0" cellpadding="0" width="100%" class="grid">' +
        // enable proxy
        '<tr><td><input type="checkbox" name="enable_proxy" id="enable_proxy" value="1"  disabled="true" /></td>' + '<td colspan="2"><label for="enable_proxy">' + lang.label('use_a_proxy') + '</label></td></tr>' +
        // proxy protocol
        '<tr><td width="28">&nbsp;</td>' + '<td>' + lang.label('proxy_protocol') + '</td>' + '<td width="70%"><input type="radio" name="protocol" id="protocol_http" value="' + lang.labelText('http') + '" checked="checked" disabled="true" />' + '<label for="protocol_http">HTTP</label></td></tr>' + '<tr><td>&nbsp;</td>' + '<td>&nbsp;</td>' + '<td><input type="radio" name="protocol" id="protocol_socks5" value="' + lang.labelText('socks5') + '" disabled="true" />' + '<label for="protocol_socks5">'+lang.label('socks5') +'</label></td></tr>' +
        // server name/IP
        '<tr><td>&nbsp;</td>' + '<td>' + lang.label('server_or_ip') + '</td>' + '<td><input type="text" name="proxy_server" id="proxy_server" maxlength="256" value="" style="width:70%" disabled="true" /></td></tr>' +
        // port
        '<tr><td>&nbsp;</td>' + '<td>' + lang.label('port') + '</td>' + '<td><input type="text" name="proxy_port" id="proxy_port" value="" size="5" maxlength="5" disabled="true" /></td></tr>' +
        // proxy authentication
        '<tr><td>&nbsp;</td>' + '<td>' + lang.label('proxy_authentication') + '</td>' + '<td>&nbsp;</td></tr>' +
        // user id
        '<tr><td>&nbsp;</td>' + '<td>' + lang.label('user_id') + ':</td>' + '<td><input type="text" name="proxy_user" id="proxy_user" maxlength="32" value="" style="width:70%" disabled="true" /></td></tr>' +
        // password
        '<tr><td>&nbsp;</td>' + '<td>' + lang.label('password') + ':</td>' + '<td><input type="password" name="proxy_password" id="proxy_password"  maxlength="32" value="" style="width:70%"  disabled="true"/></td></tr>' + '<tr><td>&nbsp;</td><td>&nbsp;</td>' +
        // save button
        '<td style="white-space:normal"><input type="button" name="serv_list_save" id="serv_list_save" value="' + lang.labelText('save_reload') + '" disabled="true" /> ' +
        // cancel button
        '<input type="button" name="serv_list_cancel" id="serv_list_cancel" value="' + lang.labelText('btn_cancel') + '" disabled="true"  /></td></tr>' + '<tr><td colspan="3">&nbsp;</td></tr>' + '</table></td></tr>' + '</table>' +

        // footer
        '<div class="footer_buttons">' + '<input type="button" name="dialog_cancel" id="dialog_cancel" value="' + lang.labelText('widget_btn_close') + '" />' + '</div>');

        $('overlay').setStyle('height', getFullHeight() + "px");
        this.updateNotesLocation();
        this.getServerData();
        $('checkAll').addEvent('click', this.checkAll.bind(this));
        $('serv_list_cancel').addEvent('click', this.cancelProxy.bind(this));
        $('serv_list_save').addEvent('click', this.sendData.bind(this));
        $('enable_proxy').addEvent('click', this.controlElements.bind(this));
        $('dialog_cancel').addEvent('click', this.dialogcanel.bind(this));
        $('proxy_toggle').addEvent('click', function () {
            $('proxy_content').setStyle('display', $('proxy_content').getStyle('display') == 'none' ? '' : 'none');
            this.showhideEditDelete($('proxy_content').getStyle('display') == 'none' ? false : true, false);
            $('proxy_toggle').className = $('proxy_toggle').className == 'btn_hide' ? 'btn_show' : 'btn_hide';
        }.bind(this)).setStyles({
            'float': 'none',
            //'padding':'0px 16px 0px 0px',
            'line-height': '20px',
            'margin-left': '6px',
            'display': 'inline-block',
            'vertical-align': 'middle'
        });
        this.adding = false;
        $('proxy_content').setStyle('display', 'none');
        $$('a.modServerListbtn_close').addEvent('click', this.dialogcanel.bind(this));

        if (this.proxyDefaultOpened && $('proxy_toggle').className == 'btn_show') {
            //this.proxyDefaultOpened = false;
            $('proxy_toggle').fireEvent('click');
        }

        if (this.NeedToopenOpts) {
            // set close button event
            $('modaloverlay').getElement('.modServerListbtn_close').addEvent('click', openOpts);
            $('dialog_cancel').addEvent('click', openOpts);
        }
        return;
    },

    refreshServerNote:function(){
      var refreshServerModal=new WFModal({title:"",content:lang.labelText("refreshservernote"),width:300,height:330}, this);
    },

    delServerNote:function(){
      var delServerModal=new WFModal({title:"",content:lang.labelText("delservernote"),width:300,height:330}, this);
    },
    
    checkAll:function(){
        var do_check=$('checkAll').checked;     
        $$('input.server_list').each(function(el){
            if(el.checked!==do_check)
            {
                el.checked=do_check;
                if(el.checked)
                {
                    if(!this.objSelectedServerHash.has(el.value))
                    {
                        this.objSelectedServerHash.set(el.value,el.value);  
                    }     
                }
                else
                {
                    if(this.objSelectedServerHash.has(el.value))
                    {
                        this.objSelectedServerHash.erase(el.value);   
                    }
                }
          }
        }.bind(this));  
    },
    dialogcanel: function () {
        if (this.serverlistcheckarray) {
            this.serverlistcheckarray.cancel();
            this.serverlistcheckarray = null;
        }
        $each(this.scanservercheckarray, function (item, key) {
            item.cancel();
        }.bind(this));
        this.scanservercheckarray = {};
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        this.closeModal();
    },

    cancelProxy: function (proxyDefaultOpened) {
        if ((typeof proxyDefaultOpened) != "boolean") {
            proxyDefaultOpened = false;
        }
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        this.proxyDefaultOpened = proxyDefaultOpened;
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_list.php?" + AddUrlParam(),
            method: 'post',
            data: JSON.encode({
                "act": "getall"
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.getProxySetting(jsonObj); }.bind(this)
            onSuccess: this.getProxySetting.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
        this.proxylistcheckarray = myJSON;
    },

    controlElements: function () {
        var isUsingProxy = $('enable_proxy').checked;
        $('protocol_http').disabled =
        $('protocol_socks5').disabled =
        $('proxy_server').disabled =
        $('proxy_port').disabled =
        $('proxy_user').disabled =
        $('proxy_password').disabled = !isUsingProxy;
    },

    getServerData: function () {
        if (this.serverlistcheckarray) {
            this.serverlistcheckarray.cancel();
            this.serverlistcheckarray = null;
        }
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            data: JSON.encode({
                "act": "getall"
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.makeContent(jsonObj); }.bind(this)
            onSuccess: this.makeContent.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
        this.serverlistcheckarray = myJSON;
    },

    //event of clicking Save
    sendData: function () {       
        var proxy_enable = 0;
        var proxy_protocol = "http";
        var proxy_host = "";
        var proxy_port = 0;
        var proxy_auth = 0;
        var proxy_username = "";
        var proxy_password = "";

        $each(this.scanservercheckarray, function (item, key) {
            item.cancel();
        }.bind(this));
        this.scanservercheckarray = {};
        if ($('enable_proxy').checked) {
            if (!isValidHost($('proxy_server').value)) {
                this.showMsg(lang.label('proxy_server_invalid'));
                return;
            }

            if (!isValidPort($('proxy_port').value)) {
                $('proxy_port').select();
                $('proxy_port').focus();
                this.showMsg(lang.label('proxy_port_invalid'));
                return;
            }

            if ($('proxy_user').get('value').length === 0 && $('proxy_password').get('value').length > 0) {
                this.showMsg(lang.label('proxy_auth_invalid'));
                return;
            }
            proxy_enable = 1;
        }
        else {
            proxy_enable = 0;
        }


        $('serv_list_save').disabled = true;

        if ($('protocol_http').checked) {
            proxy_protocol = "http";
            if ($('proxy_user').value.length > 0 || $('proxy_password').value.length > 0) {
                proxy_auth = 1;
            }
            else {
                proxy_auth = 0;
            }
        }
        else if ($('proxy_user').value.length > 0 || $('proxy_password').value.length > 0) {
            proxy_protocol = "sock5";
            proxy_auth = 1;
        }
        else {
            proxy_protocol = "sock5";
            proxy_auth = 0;
        }

        proxy_host = $('proxy_server').value;
        proxy_port = $('proxy_port').value;
        proxy_username = $('proxy_user').value;
        proxy_password = $('proxy_password').value;

        var proxyobject = {};


        var data_info;
        if (this.firstproxyid) {
            proxyobject = {
                "act": "update",
                "proxyid": this.firstproxyid,
                "name": "",
                "proxyinfo": {
                    "host": proxy_host,
                    "port": parseInt(proxy_port,10),
                    "type": proxy_protocol,
                    "auth": proxy_auth,
                    "username": proxy_username,
                    "password": proxy_password,
                    "enable": proxy_enable
                }
            };
        }
        else {
            //data_info= 'act=add'+'&name=""&proxyinfo='+JSON.encode(proxyobject);
            proxyobject = {
                "act": "add",
                "name": "",
                "proxyinfo": {
                    "host": proxy_host,
                    "port": parseInt(proxy_port,10),
                    "type": proxy_protocol,
                    "auth": proxy_auth,
                    "username": proxy_username,
                    "password": proxy_password,
                    "enable": proxy_enable
                }
            };
        }

        data_info = JSON.encode(proxyobject);
        // sending data
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_list.php?" + AddUrlParam(),
            method: 'post',
            data: data_info,
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.setProxySetting(jsonObj); }.bind(this)
            onSuccess: this.setProxySetting.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();


    },

    //setProxySetting:function(jsonObj){
    setProxySetting: function (responseObj) {
        var jsonObj = responseObj[1];
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 300:
            case 301:
            case 302:
            case 303:
            case 304:
            case 305:
            case 306:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('set_proxy_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('set_proxy_failed') + "<BR>" + message);
            this.cancelProxy(true);
            return;
        }

        if (!this.firstproxyid) {
            this.firstproxyid = jsonObj.result;
        }

        var data_info;

        if ($('enable_proxy').checked) {
            data_info = JSON.encode({
                "enable": 1,
                "proxyid": this.firstproxyid
            });
        }
        else {
            data_info = JSON.encode({
                "enable": 0
            });
        }
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_enable.php?" + AddUrlParam(),
            method: 'post',
            data: data_info,
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.enableordisableProxy(jsonObj,null,true); }.bind(this)
            uid: null,
            needRefresh: true,
            onSuccess: this.enableordisableProxy.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
    },


    //enableordisableProxy:function(jsonObj,uid,needRefresh){
    enableordisableProxy: function (responseObj) {
        jsonObj = responseObj[1];
        uid = responseObj[2].options.uid;
        needRefresh = responseObj[2].options.needRefresh;
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 500:
            case 501:
            case 502:
            case 503:
            case 504:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('proxy_enable_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('proxy_enable_failed') + "<BR>" + message);
            return;
        }

        if (needRefresh) {
            this.proxyDefaultOpened = true;
            this.onFinish();
        }

        //this.closeModal();
    },

    fillLastUpdate: function () {
        if ($('updateText') === null) {
            return;
        }
        this.updateText = $('updateText').setHTML(lang.label('last_check') + new Date().formatDate(lang.label('dateformat')));
        /*
        new Element('img', {
            'events': {
                'click': this.refresh.bind(this)
            },
            'class': 'refresh_server',
            'title': lang.labelText('refresh'),
            'src': this.refresh_icon,
            'style': 'display:' + (($('proxy_toggle').className == 'btn_hide') ? 'none' : 'inline-block')
        }).injectInside($('updateText'));
        */
    },
    // event of refresh icon
    refresh: function () {
        // window.location.reload();
        if (this.serverlistcheckarray) {
            this.serverlistcheckarray.cancel();
            this.serverlistcheckarray = null;
        }
        $each(this.scanservercheckarray, function (item, key) {
            item.cancel();
        }.bind(this));
        this.scanservercheckarray = {};
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        this.lost_connection = [];
        this.timeout_connection = [];
        this.proxyDefaultOpened = null;
        this.objSelectedServerHash.empty();
        this.onFinish();
    },
    //makeContent: function(jsonObj){
    makeContent: function (responseObj) {
        var jsonObj = responseObj[1];
        if (!$chk(jsonObj)) {
            return;
        }
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('get_serverlist_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('get_serverlist_failed') + "<BR>" + message);
            return;
        }
        var table = $(this.table_id);
        var servers = jsonObj.result;
        g_serverlist.setServerList(servers);
        g_serverlist.adjustLastCheckTimedifference();
        this.fillLastUpdate();
        if ($('add_server') === null) {
            return;
        }
        $('add_server').set('value',lang.labelText('add_server')).set('disabled', ($('proxy_toggle').className == 'btn_hide') ? true : false);
        $('del_server').set('value',lang.labelText('del_server')).set('disabled', ($('proxy_toggle').className == 'btn_hide') ? true : false);
        $('refresh_server').set('value',lang.labelText('refresh')).set('disabled', ($('proxy_toggle').className == 'btn_hide') ? true : false);
        this.scanservercheckarray = {};
        if (servers.length > 0) {
            this.servData = {};
            this.ajaxCount = servers.length; // how many ajax connections will be made
            this.currentCount = 0;
            // show all lost connection message in once
            var showSingle = false;
            // got probelms on $each in IE7 when iterable is from XML 
            // using [for] here
            for (var index = 0; index < servers.length; index++) {
                var item = {
                    name: servers[index].name,
                    type: servers[index].hostinfo.type,
                    account: (servers[index].name == "localhost") ? "" : servers[index].hostinfo.username,
                    password: (servers[index].name == "localhost") ? "" : servers[index].hostinfo.password
                };
                this.makeRow(item, servers[index].id);
                this.checkStatus(servers[index].id, servers[index].hostinfo.type, showSingle, (index + 2) - servers.length);
            }
            this.waitingData();
        }
        if (this.proxylistcheckarray) {
            this.proxylistcheckarray.cancel();
            this.proxylistcheckarray = null;
        }
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/proxy_list.php?" + AddUrlParam(),
            method: 'post',
            data: JSON.encode({
                "act": "getall"
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj){ this.getProxySetting(jsonObj); }.bind(this)
            onSuccess: this.getProxySetting.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
        this.proxylistcheckarray = myJSON;

    },

    getProxySetting: function (responseObj) {
        jsonObj = responseObj[1];
        //it means user close dialog
        if (!$chk(jsonObj)) {
            return;
        }
        // fill proxy setting
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 300:
            case 301:
            case 302:
            case 303:
            case 304:
            case 305:
            case 306:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('get_proxylist_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('get_proxylist_failed') + "<BR>" + message);
            return;
        }

        if (jsonObj.result.length === 0) {
            $('enable_proxy').checked = false;
            $('protocol_http').checked = true;
            $('proxy_server').value = "";
            $('proxy_port').value = "";
            $('proxy_user').value = "";
            $('proxy_password').value = "";
        }
        else {

            this.firstproxyid = jsonObj.result[0].id;
            $('enable_proxy').checked = (jsonObj.result[0].hostinfo.enable == 1) ? true : false;
            if (jsonObj.result[0].hostinfo.type == "http") {
                $('protocol_http').checked = true;
            }
            else {
                $('protocol_socks5').checked = true;
            }
            $('proxy_server').value = jsonObj.result[0].hostinfo.host;
            $('proxy_port').value = (jsonObj.result[0].hostinfo.port) ? jsonObj.result[0].hostinfo.port : "";
            $('proxy_user').value = jsonObj.result[0].hostinfo.username;
            $('proxy_password').value = jsonObj.result[0].hostinfo.password;
        }
        this.controlElements();
        $('enable_proxy').disabled = false;
        $('serv_list_save').disabled = false;
        $('serv_list_cancel').disabled = false;
        $('add_server').addEvent('click', this.addServer.bind(this));
        $('del_server').addEvent('click', this.delServer.bind(this));
        $('refresh_server').addEvent('click', this.refresh.bind(this));
        // is canceling/closing proxy setitng
        if (this.proxyDefaultOpened === false && $('proxy_toggle').className == 'btn_hide') {
            this.proxyDefaultOpened = null;
            //$('messageBox').setHTML('').className = null;
            $('proxy_toggle').fireEvent('click');
        }

    },
    
    delServer:function(){
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        if(this.objSelectedServerHash.getLength()===0)
        {
            this.showMsg(lang.label('at_least_one_server'));
            return;
        }
        if (!confirm(lang.labelText('confirm_delete'))) {
            return;
        }
        var strIDlist=this.objSelectedServerHash.getKeys().join(",");
        // sent deleting data to server
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            parameter: strIDlist,
            data: JSON.encode({
                "act": "batchdelete",
                "serverids":strIDlist 
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            onSuccess: this.deleteServerResponse.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();      
    },
    
    updatecheckAllBox:function(){
        var finalresult=true;
        $$('input.server_list').each(function(el){
            finalresult=finalresult&el.checked;    
        });
        $('checkAll').checked=finalresult;    
    },
    
    updateSelectedServer:function(e){
        var event = new Event(e);
        if(event.target.checked)
        {
            if(!this.objSelectedServerHash.has(event.target.value))
            {
                this.objSelectedServerHash.set(event.target.value,event.target.value);  
            }     
        }
        else
        {
            if(this.objSelectedServerHash.has(event.target.value))
            {
                this.objSelectedServerHash.erase(event.target.value);   
            }   
        }
        this.updatecheckAllBox();   
    },
    makeRow: function (item, uid) { //item = {name:'name',account:'account',password:'password'}
        var table = $(this.table_id);
        var row = table.insertRow(table.rows.length);
        var index = row.rowIndex;
        if (index % 2 === 0) {
            $(row).addClass('even');
        }
        row.setAttribute('id', uid);
        this.servData[uid] = item;
        var td_0 = new Element('td', {
          'style': 'text-align:center;'
        }).injectInside(row);
        if(index>1)
        {
          td_0.setHTML('<input type="checkbox" class="server_list" value="'+uid+'">');
          td_0.getElement('input').addEvent('click',this.updateSelectedServer.bind(this));
        }
        var td_1 = new Element('td', {
            'style': 'text-align:center;'
        }).setHTML("<table><tr><td style='border-left:0px' width='5%'>" + this.status_img + "</td><td style='border-left:0px' width='95%'><div class='ServerNameorIPWrap' title='" + item.name + "' style='width:350px'>" + item.name + "</div></td></tr></table>").injectInside(row);
        /*var td_2 = new Element('td', {
            'class': 'connection_status'
        }).setHTML(lang.label("connection_testing")).injectInside(row);*/
        /*var td_4 = new Element('td').injectInside(row);*/
        var td_2 = new Element('td',{
            'style': 'text-align:left;'
        }).setHTML("<div class='ServerNameorIPWrap' title='" + lang.label(item.type) + "' style='width:300px'>" + lang.label(item.type) + "</div>").injectInside(row);
        var td_3 = new Element('td').injectInside(row);
        if (item.name != "localhost" && uid != "1") {
            var edit_link = new Element('a', {
                'events': {
                    'click': this.editServer.bind(this)
                },
                //'href': 'javascript:void(0);',
                'class': 'edit_icon',
                'title': lang.labelText('edit'),
                'style': 'display:' + (($('proxy_toggle').className == 'btn_hide') ? 'none' : 'block')
            }).injectInside(td_3);
            /*
            var delete_link = new Element('a', {
                'events': {
                    'click': function (e) {
                        this.deleteServer(e);
                    }.bind(this)
                },
                //'href': 'javascript:void(0);',
                'class': 'delete_icon',
                'title': lang.labelText('delete'),
                'style': 'display:' + (($('proxy_toggle').className == 'btn_hide') ? 'none' : 'block')
            }).injectInside(td_4);
            */
        } else {
            td_3.setHTML('&nbsp;');
            if (custom_options.hide_localhost) {
                $(row).setStyle("display", "none");
            }
        }
    },

    // check the connecttion status of a server
    checkStatus: function (uid, type, showSingle, showAll) {
        var myJSON = new WFRequest.JSON({
            url: homeBase + proxyHandler + "?" + AddUrlParam() + "&act=check&module=" + type + "&serverid=" + uid,
            timeout: ajaxTimeoutValue,
            //onTimeout: function() {this.onTimeOut(uid);}.bind(this),
            //onSuccess: function(jsonObj){this.changeStatus(jsonObj,uid,showSingle,showAll||false); }.bind(this)
            uid: uid,
            showsingle: showSingle,
            showall: showAll || false,
            onFailure: this.onFailure.bind(this),
            onSuccess: this.changeStatus.bind(this)
        });
        myJSON.send();
        this.scanservercheckarray[uid] = myJSON;
    },


    onFailure: function (reqObj) {
        if (reqObj.isTimeout === true) {
            this.onTimeOut.bind(this)(reqObj);
            return;
        }
        var uid = reqObj.options.uid;
        var img = $(uid).getElementsByTagName('img')[0];
        var connection_status = $(uid).getElement("td.connection_status");
        //$(connection_status).setHTML(lang.label("failed"));
        var status = 'offline';
        img.src = homeBase + 'img/default/server_' + status + '_16.gif';
        img.title = lang.labelText(status);
        this.lost_connection.push(uid);
        $(uid).addClass('lost_connection');
        this.currentCount++; // means it's done
        if (this.currentCount == this.ajaxCount) {
            this.isAjaxDone = true;
        }
    },
    //onTimeOut:function(uid){ 
    onTimeOut: function (reqObj) {
        var uid = reqObj.options.uid;
        if ($('updateText').getProperty('save_click') == 'true') {
            this.showMsg(lang.label('timeout_connect') + ' ' + $(uid).getElement("div.ServerNameorIPWrap").get('text'));
            $('updateText').setProperty('save_click', 'false');
        }
        var img = $(uid).getElementsByTagName('img')[0];
        var connection_status = $(uid).getElement("td.connection_status");
        //$(connection_status).setHTML(lang.label("timeout"));
        var status = 'offline';
        img.src = homeBase + 'img/default/server_' + status + '_16.gif';
        img.title = lang.labelText(status);
        this.timeout_connection.push(uid);
        $(uid).addClass('lost_connection');
        this.currentCount++; // means it's done
        if (this.currentCount == this.ajaxCount) {
            this.isAjaxDone = true;
        }
    },
    // called on-complete of checkStatus, change the status icon and makeing the message box 
    //changeStatus: function(jsonObj, uid, showSingle, showAll){
    changeStatus: function (reqObj) {
        var jsonObj = reqObj[1];
        var uid = reqObj[2].options.uid;
        var showSingle = reqObj[2].options.showsingle;
        var showAll = reqObj[2].options.showall;

        if (!$chk(jsonObj) || $(uid) === null) {
            return;
        }

        var img = $(uid).getElementsByTagName('img')[0];
        //var connection_status = $(uid).getElement("td.connection_status");
        var status = jsonObj.errcode === 0 ? 'online' : 'offline';
        if(img)
        {
            img.src = homeBase + 'img/default/server_' + status + '_16.gif';
            img.title = lang.labelText(status);
        }
        if (status == 'offline') {
            if (jsonObj.errcode == 423) {
                this.timeout_connection.push(uid);
                //$(connection_status).setHTML(lang.label("timeout"));
            }
            else {
                this.lost_connection.push(uid);
                //$(connection_status).setHTML(lang.label("failed"));
            }
            $(uid).addClass('lost_connection');
            g_serverlist.updateLastCheck(uid, 0);
        } else {
            $(uid).removeClass('lost_connection');
            //$(connection_status).setHTML(lang.label("success"));
            g_serverlist.updateLastCheck(uid, new Date().getTime());
        }

        if (showSingle) {
            this.showMsg(
            status == 'offline' ? // message content
            lang.label('failed_connect') + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") : lang.label('add_sucessful_1') + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") + lang.label('add_sucessful_2'), status == 'offline' ? 'error' : 'notice' // message type
            );
        }

        this.currentCount++; // means it's done
        if (this.currentCount == this.ajaxCount) {
            this.isAjaxDone = true;
        }
    },

    // Event of Add Server button
    addServer: function (e) {
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        this.editServer(e);
        $(this.table_id).addClass('adding');
        this.adding = true;
    },

    // Event of edit button, this function will be share with event of Adding button
    editServer: function (e) {
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        // hide add server button when add/edit server
        if (this.adding) {
            return;
        }
        $('add_server').set('disabled', true);
        $('del_server').set('disabled', true);
        $('refresh_server').set('disabled', true);
        var tr,sName,account,password;
        var table = $(this.table_id);
        var event = new Event(e);
        var uid = event.target.id == 'add_server' ? // add or edit, if is adding, uid=''
        '' : event.target.parentNode.parentNode.id;
        if (uid !== '') { // editing a server
            tr = table.insertRow($(uid).rowIndex);
            if ($(uid).hasClass('even')) {
                $(tr).addClass('even');
            }
            $(uid).style.display = 'none';
            sName = this.servData[uid].name;
            account = this.servData[uid].account;
            password = ($defined(this.servData[uid].password))?this.servData[uid].password:'';
        } else { // adding a new server
            tr = table.insertRow(table.rows.length);
            if (tr.rowIndex % 2 === 0) {
                $(tr).addClass('even');
            }
            sName = '';
            account = '';
            password = '';
        }

        var td = new Element('td', {
            'colspan': 4,
            'class': 'edit_in_place'
        }).injectInside(tr);
        var new_table = new Element('table', {
            'width': '75%',
            'class': 'grid',
            'cellspacing': '4'
        }).injectInside(td);
        new_table.setStyle('margin-left', '55px');
        var input_name = '<input type="text" name="server_name"  class="textfield" id="server_name" size="60" maxlength="255"  value="' + sName + '" /><div class="hint">' + lang.label("server_example") + '</div>';
        var input_account = '<input type="text" name="account"   class="textfield"  size="50" maxlength="32" value="' + account.replace(/"/g, '&quot;') + '" />';
        var input_pass = '<input type="password" name="password"  class="textfield" size="50" maxlength="32"  value="' + password.replace(/"/g, '&quot;') + '" />';

        var input_type = new Element('select', {
            'id': 'server_type',
            'name': 'server_type'
        });
        input_type.setStyle('width','300px');
        var serverlisttype = g_serverlist.getServerListType();
        $each(serverlisttype, function (item, index) {
            new Element('option', {
                'title': lang.labelText(item.type),
                'value': item.type,
                'text': lang.labelText(item.type)
            }).inject(input_type);
        }.bind(this));

        var tr_1 = new_table.insertRow(new_table.rows.length);
        var tr_5 = new_table.insertRow(new_table.rows.length);
        var tr_2 = new_table.insertRow(new_table.rows.length);
        var tr_3 = new_table.insertRow(new_table.rows.length);
        var tr_4 = new_table.insertRow(new_table.rows.length);


        new Element('td', {
            'width': '10%'
        }).injectInside(tr_1).setHTML(lang.label('server_name'));
        new Element('td').injectInside(tr_1).setHTML(input_name);
        new Element('td').injectInside(tr_2).setHTML(lang.label('account'));
        var accountcontainer = new Element('td').injectInside(tr_2).setHTML(input_account);
        input_type.addEvent('change', function (event) {
            if (g_serverlist.isPasswordOnly(this.value)) {
                $(accountcontainer).getElement('input').disabled = 1;
            }
            else {
                $(accountcontainer).getElement('input').disabled = 0;
            }
        });
        new Element('td').injectInside(tr_3).setHTML(lang.label('password'));
        new Element('td').injectInside(tr_3).setHTML(input_pass);
        new Element('td').injectInside(tr_5).setHTML(lang.label('type'));
        var selectcontainer = new Element('td').injectInside(tr_5);
        input_type.inject(selectcontainer);
        new Element('td').injectInside(tr_4).setHTML('&nbsp;');
        var btn_td = new Element('td').injectInside(tr_4);
        if (uid !== '') {
            $(tr_5).getElement('#server_type').set('value', this.servData[uid].type);
            $(tr_5).getElement('#server_type').set('title', lang.labelText(this.servData[uid].type));
            if (g_serverlist.isPasswordOnly(this.servData[uid].type)) {
                $(accountcontainer).getElement('input').disabled = 1;
            }
            else {
                $(accountcontainer).getElement('input').disabled = 0;
            }
        }
        var save = new Element('input', {
            'id': 'update_or_add_save_button',
            'type': 'button',
            'value': lang.label('btn_save'),
            'events': {
                'click': function () {
                    this.saveServer(uid, tr);
                }.bind(this)
            }
        }).injectInside(btn_td);
        var cancel = new Element('input', {
            'id': 'update_or_add_cancel_button',
            'type': 'button',
            'value': lang.label('btn_cancel'),
            'events': {
                'click': function () {
                    $('messageBox').setHTML('').className = null;
                    this.cancelServer(uid, tr);
                    this.showhideEditDelete(false, true);
                    this.updateNotesLocation();
                }.bind(this)
            }
        }).injectInside(btn_td);

        //hide edit delete buttons
        this.showhideEditDelete(true, true);
        // set focus on server name
        tr_1.getElementsByTagName('input')[0].focus();
        tr_1.getElementsByTagName('input')[0].select();

        return;
    },


    showhideEditDelete: function (displayvalue, includeProxyToggle) {
      var strDisplayValue="";
        if (false === displayvalue) {
          strDisplayValue="block";
            if ($chk(this.contentBox.getElement("img.refresh_server"))) {
                this.contentBox.getElement("img.refresh_server").setStyle("display", "inline-block");
            }
            if (includeProxyToggle) {
                $('proxy_toggle').setStyle("display", "inline-block");
            }
        }
        else {
          strDisplayValue="none";
            if ($chk(this.contentBox.getElement("img.refresh_server"))) {
                this.contentBox.getElement("img.refresh_server").setStyle("display", strDisplayValue);
            }
            if (includeProxyToggle) {
                $('proxy_toggle').setStyle("display", strDisplayValue);
            }
        }
        if (!includeProxyToggle) {
            $('add_server').set('disabled', displayvalue);
            $('del_server').set('disabled', displayvalue);
            $('refresh_server').set('disabled', displayvalue);
        }
        this.contentBox.getElements("a.edit_icon").setStyle("display", strDisplayValue);
        //this.contentBox.getElements("a.delete_icon").setStyle("display", strDisplayValue);
    },


    // save the setting of edit
    saveServer: function (uid, tr) {
        $('updateText').setProperty('save_click', 'true');
        // data validation
        var url = trimString(tr.getElementsByTagName('input')[0].value.toLowerCase());

        var objUrlProcessor = new WFUrlProcessor(url);
        if (!objUrlProcessor.isValid()) {
            tr.getElementsByTagName('input')[0].select();
            tr.getElementsByTagName('input')[0].focus();
            this.showMsg(lang.label('url_invalid'));
            return;
        }

        var UriObj = objUrlProcessor.objUrl;
        if ((UriObj.path.length > 0 && UriObj.path !== "/") || (UriObj.protocol.toLowerCase() !== "http" && UriObj.protocol.toLowerCase() !== "https")) {
            this.showMsg(lang.label('url_invalid'));
            return;
        }

        if (UriObj.port === "") {
            if (UriObj.protocol.toLowerCase() ==="http") {
                UriObj.port = 80;
            }
            else {
                UriObj.port = 443;
            }
        }

        var samename = false;
        $each(this.servData, function (item, index) {
            if (item.name != "localhost"){                
                var servDataUriObj = parseUrl(item.name);                
                if (servDataUriObj.port === "") {
                    servDataUriObj.port = ((servDataUriObj.protocol.toLowerCase() == "http") ? 80 : 443);
                }
                if (UriObj.source.toLowerCase() === servDataUriObj.source.toLowerCase()) {
                    if (!uid) {
                        this.showMsg(lang.label('duplicated_server'));
                        samename = true;
                    }
                    else {
                        if (parseInt(uid,10) != index) {
                            this.showMsg(lang.label('duplicated_server'));
                            samename = true;
                        }
                    }
                }
            }
        }.bind(this));
        // UI change
        if (samename) {
            return;
        }
        $('messageBox').setStyles({
            'display': 'block',
            'height': 'auto',
            'backgroundColor': ''
        }).setHTML('').className = '';
        $('update_or_add_save_button').disabled = true;
        $('update_or_add_cancel_button').disabled = true;
        var data_info;
        var serverinfo = {};
        var servertypeselectelment = tr.getElementsByTagName('select')[0];
        // sync data in object
        if (uid) { //edit
      this.servData[uid].name= url;
      this.servData[uid].account=tr.getElementsByTagName('input')[1].value;
      this.servData[uid].password=tr.getElementsByTagName('input')[2].value;
      this.servData[uid].type=servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value;
            serverinfo = {
                "act": "update",
                "name": url,
                "serverid": uid,
                "serverinfo": {
                    "host": UriObj.host.toLowerCase(),
                    "port": UriObj.port,
                    "protocol": UriObj.protocol.toLowerCase(),
                    "username": tr.getElementsByTagName('input')[1].value,
                    "password": tr.getElementsByTagName('input')[2].value,
                    "proxy_enable": ($('enable_proxy').checked) ? 1 : 0,
                    "proxy_id": this.firstproxyid,
                    "type": servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value
                }
            };
        } else { //add
            //data_info='act=add'+'&name='+tr.getElementsByTagName('input')[0].value+"&serverinfo="+JSON.encode(serverinfo);
            serverinfo = {
                "act": "add",
                "name": url,
                "serverinfo": {
                    "host": UriObj.host.toLowerCase(),
                    "port": UriObj.port,
                    "protocol": UriObj.protocol.toLowerCase(),
                    "username": tr.getElementsByTagName('input')[1].value,
                    "password": tr.getElementsByTagName('input')[2].value,
                    "proxy_enable": ($('enable_proxy').checked) ? 1 : 0,
                    "proxy_id": this.firstproxyid,
                    "type": servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value
                }
            };
        }

        data_info = JSON.encode(serverinfo);
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            data: data_info,
            parameter: tr,
            parameter2: uid,
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj,text,obj){ (uid)?this.updateServer(jsonObj,text,obj):this.addNewServer(jsonObj,text,obj); }.bind(this)
            onSuccess: (uid) ? this.updateServer.bind(this) : this.addNewServer.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
    },

    //updateServer:function(jsonObj,text,obj){
    updateServer: function (responseObj) {
        jsonObj = responseObj[1];
        text = responseObj[0];
        obj = responseObj[2];
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('edit_scanserver_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('edit_scanserver_failed') + "<BR>" + message);
            return;
        }
        this.showhideEditDelete(false, true);
        this.servData[obj.options.parameter2].name = obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase();
        this.servData[obj.options.parameter2].account = obj.options.parameter.getElementsByTagName('input')[1].value;
        this.servData[obj.options.parameter2].password = obj.options.parameter.getElementsByTagName('input')[2].value;
        var servertypeselectelment = obj.options.parameter.getElementsByTagName('select')[0];
        g_serverlist.updateName(obj.options.parameter2, obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase());
        // update row content
        //$(obj.options.parameter2).cells[1].setHTML(lang.label("connection_testing"));
        $(obj.options.parameter2).cells[2].setHTML("<div class='ServerNameorIPWrap' title='" + lang.label(obj.options.parameter.getElementsByTagName('select')[0].value) + "' style='width:300px'>" + lang.label(obj.options.parameter.getElementsByTagName('select')[0].value) + "</div>");
        this.ajaxCount = 1;
        this.currentCount = 0;
        this.checkStatus(obj.options.parameter2, servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value, true);
        this.waitingData();
        $(this.table_id).deleteRow(obj.options.parameter.rowIndex);
        this.recoverButtons(obj.options.parameter2);
        if ($chk($(obj.options.parameter2).cells[1].getElement("img.status_img"))) {
            $(obj.options.parameter2).cells[1].getElement("img.status_img").src = homeBase + "img/default/widgetLoading.gif";
        }
        var ServerNameorIP = $(obj.options.parameter2).cells[1].getElements("td")[1];
        if ($chk(ServerNameorIP)) {
            $(ServerNameorIP).setHTML("<div class='ServerNameorIPWrap' title='" + this.servData[obj.options.parameter2].name + "' style='width:300px'>" + this.servData[obj.options.parameter2].name + "</div>");
        }
    },

    //addNewServer:function(jsonObj,text,obj){
    addNewServer: function (responseObj) {
        jsonObj = responseObj[1];
        text = responseObj[0];
        obj = responseObj[2];
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            ////alert(lang.label('add_scanserver_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('add_scanserver_failed') + "<BR>" + message);
            return;
        }
        this.showhideEditDelete(false, true);
        var uid = jsonObj.result;
        var servertypeselectelment = obj.options.parameter.getElementsByTagName('select')[0];
        // make a row in UI
        var item = {
            name: obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase(),
            type: servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value,
            account: obj.options.parameter.getElementsByTagName('input')[1].value,
            password: obj.options.parameter.getElementsByTagName('input')[2].value
        };
        // sync data
        this.servData[uid] = item;

        var UriObj = parseUrl(obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase());
        g_serverlist.addOneServer({
            "id": uid,
            "name": obj.options.parameter.getElementsByTagName('input')[0].value.toLowerCase(),
            "lastcheck": 0,
            "hostinfo": {
                "host": UriObj.host.toLowerCase(),
                "port": UriObj.port,
                "protocol": UriObj.protocol.toLowerCase()
            }
        });
        // check status
        this.ajaxCount = 1;
        this.currentCount = 0;
        this.checkStatus(uid, servertypeselectelment.options[servertypeselectelment.options.selectedIndex].value, true);
        this.waitingData();
        // recover hidden buttons
        $(this.table_id).deleteRow(obj.options.parameter.rowIndex);
        this.recoverButtons('');
        // make a row for new server
        this.makeRow(item, uid);
    },


    // cancel the setitng of edit
    cancelServer: function (uid, tr) {
        $(this.table_id).deleteRow(tr.rowIndex);
        this.recoverButtons(uid);
    },

    // recover UI elements when editing is done
    recoverButtons: function (uid) {
        if (uid) { // edting a data
            $(uid).setStyle('display', '');
        } else { // adding new data
            this.adding = false;
            $(this.table_id).removeClass('adding');
        }
        $('add_server').set('disabled', false);
        $('del_server').set('disabled',  false);
        $('refresh_server').set('disabled',  false);
    },

    // event of delete button
    deleteServer: function (e) {
        if (!this.isAjaxDone || $('enable_proxy').disabled === true) {
            return;
        }
        if (!confirm(lang.labelText('confirm_delete'))) {
            return;
        }
        var event = new Event(e);
        var uid = event.target.parentNode.parentNode.id;
        var tr = $(uid);

        // sent deleting data to server
        var myJSON = new WFRequest.JSON({
            url: homeBase + "inc/server_list.php?" + AddUrlParam(),
            method: 'post',
            parameter: tr,
            parameter2: uid,
            data: JSON.encode({
                "act": "delete",
                "serverid": uid
            }),
            urlEncoded: false,
            headers: {
                "Content-type": "application/json"
            },
            //onSuccess: function(jsonObj,text,obj){ this.deleteServerResponse(jsonObj,text,obj); }.bind(this)
            onSuccess: this.deleteServerResponse.bind(this)
        });
        myJSON.addEvent('onFailure', this.ajaxFailed);
        myJSON.send();
    },


    //deleteServerResponse:function(jsonObj,text,obj){
    deleteServerResponse: function (responseObj) {
        jsonObj = responseObj[1];
        text = responseObj[0];
        obj = responseObj[2];
        // UI refresh
        if (jsonObj.errcode !== 0) {
            var message = "";
            switch (jsonObj.errcode) {
            case 200:
            case 201:
            case 202:
            case 203:
            case 204:
            case 205:
            case 206:
                message += lang.label("errorcode_" + jsonObj.errcode);
                break;
            default:
                message += lang.label("errorcode_undefined");
            }
            //alert(lang.label('delete_scanserver_failed')+" ("+lang.label('error')+jsonObj.errcode+")");
            this.showMsg(lang.label('delete_scanserver_failed') + "<BR>" + message);
            return;
        }
        var arraylist = g_serverlist.getServerList();
        var arrServerList=obj.options.parameter.split(",");
        for (var i= 0,l=arrServerList.length; i< l; i++) {
            delete this.servData[arrServerList[i]];
            $(this.table_id).deleteRow($(arrServerList[i]).rowIndex);
            this.objSelectedServerHash.erase(arrServerList[i]);
loop:
            for (var index = arraylist.length - 1; index >= 0; index--) {
                if (arraylist[index].id == arrServerList[i]) {
                    g_serverlist.deleteOneServer(index);
                    break loop;
                }
            }
        }
        $('checkAll').checked=false;
        this.checkAll();
        this.tableRefresh();
    },

    //refresh the color of odd and even rows 
    tableRefresh: function () {
        var rows = $(this.table_id).rows;
        var m = 0;
        var r = 1;
        $each(rows, function (item, index) {
            if (index === 0) {
                return true;
            }
            if (item.style.display === 'none') {
                // revert m and r if encounter a editing column
                r = 0;
                m = 1;
            }
            if (index % 2 == m) {
                item.addClass('even');
            } else if (index % 2 == r) {
                item.removeClass('even');
            }
        });
    },

    // waiting for ajax done and make message box
    waitingData: function () {
        this.isAjaxDone = false;
        this.waitHandler = setTimeout(function () {
            this.waitCheck();
        }.bind(this), 500);
    },
    waitCheck: function () 
	{
        // don't display error when check all serevrs
		//return;
        if (!this.isAjaxDone) {
            setTimeout(function () {
                this.waitCheck();
            }.bind(this), 500);
        } else if (this.lost_connection.length > 0 || this.timeout_connection.length > 0) {
            //making message box
            var msg_str = '';
            var timeoutmsg_str = '';
            var counter = 0;
            var timeoutcounter = 0;
            var displaymessage;
            $each(this.lost_connection, function (uid, i) {            
                if (this.servData[uid] && this.servData[uid].name) {
                    msg_str += '<div>' + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") + '</div>';
                    counter++;
                }
            }.bind(this));
            if (counter > 0) {
                displaymessage = lang.label('failed_connect') + msg_str;
            }
            $each(this.timeout_connection, function (uid, i) {
                if (this.servData[uid] && this.servData[uid].name) {
                    timeoutmsg_str += '<div>' + this.servData[uid].name.wordWrap(serverwrapcharscount, "<BR>") + '</div>';
                    timeoutcounter++;
                }
            }.bind(this));
            if (counter > 0 && timeoutcounter > 0) {
               displaymessage = displaymessage + "<BR>" + lang.label('timeout_connect') + timeoutmsg_str;
            }
            else if (counter === 0 && timeoutcounter > 0) {
                displaymessage = lang.label('timeout_connect') + timeoutmsg_str;
            }
            if (counter > 0 || timeoutcounter > 0) {

                this.showMsg(displaymessage, 'error');

            }
            //showServerOffline();
            this.lost_connection = [];
            this.timeout_connection = [];
        }
    },


    // failed handler
    ajaxFailed: function () {
         $('checkAll').checked=false;
         this.checkAll();
    }
});